package cn.pconline.autoclub.mq;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.gelivable.dao.GeliDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import cn.pconline.autoclub.entity.MqMessageLog;

import com.alibaba.fastjson.JSONObject;


/**
 * @author zhouruxuan
 * @date 2014年12月3日 上午10:12:32
 */
public class MessageListener {
    private static final Logger log = LoggerFactory.getLogger(MessageListener.class);
    
    private static final String ROUTE_KEY = "routeKey";

    private Map<String, List<ClubMessageHandler>> handlers;
    
    public void setHandlers(Map<String, List<ClubMessageHandler>> handlers) {
        this.handlers = handlers;
    }
    
    @Autowired
    private GeliDao geliDao;

    /**
     * 监听器，接收MQ信息的主方法
     *
     * @param obj
     */
    public void onMessage(JSONObject obj) {
        if (obj == null) {
            return;
        }
        log.info("Message in: {}", obj.toJSONString());
        //创建mq msg 记录
        try {
            createMqMsgLog(obj);
        } catch (Exception ex) {
            log.error("create message[{}] log error: {} ", obj.toJSONString(), ex.getMessage());
        }
        
        List<ClubMessageHandler> list = handlers.get(obj.getString(ROUTE_KEY));
        if (list == null) {
            log.info("No mapping handler.");
            return;
        }
        for (ClubMessageHandler handler : list) {
            if(handler == null) {
                log.warn("this is a null handler try to process msg: {}", obj.toJSONString());
                continue;
            }
            try {
                handler.handleJsonMessage(obj);
            } catch (Exception e) {
                log.error("{} process message[{}] error.", handler.getClass().getSimpleName(), obj.toJSONString());
                log.error("Process message failed.", e);
            }
        }
    }
    
    private MqMessageLog createMqMsgLog(JSONObject obj) {
        MqMessageLog log = new MqMessageLog();
        log.setRouteKey(obj.getString(ROUTE_KEY));
        log.setMessage(obj.toJSONString());
        log.setCreateAt(new Date());
        geliDao.create(log);
        return null;
    }
}
